package com.segersten.kalaha;

import com.google.appengine.api.memcache.MemcacheServiceFactory
import com.google.appengine.api.memcache.MemcacheService

class PlayerCache {

	def put = { Player player -> 
		MemcacheService cacheBySessionId = MemcacheServiceFactory.getMemcacheService("PlayerCache")
		MemcacheService cacheClientId = MemcacheServiceFactory.getMemcacheService("PlayerClientIdCache")
	    if (!cacheBySessionId) {
	    		throw new RuntimeException("Failed to look up PlayerCache")
	    }
	    if (!cacheClientId) {
	    		throw new RuntimeException("Failed to look up PlayerClientIdCache")
	    }
	    if (!player) {
	    		thrown new IllegalArgumentException("Player cannot be null");
	    }
	    if (!player.userId) {
	    		thrown new IllegalArgumentException("Player's userId cannot be null");
	    }
	    if (!player.sessionId) {
	    		thrown new IllegalArgumentException("Player's sessionId cannot be null");
	    }
	    cacheBySessionId.put(player.sessionId, player)
	    cacheClientId.put(player.userId, player.sessionId)
	}
	
	def getByUserId = { String id ->
	    MemcacheService cacheClientId = MemcacheServiceFactory.getMemcacheService("PlayerClientIdCache")

	    if (!cacheClientId) {
	    		throw new RuntimeException("Failed to look up PlayerClientIdCache")
	    }
	    getBySessionId(cacheClientId.get(id))
	}
	
	def getBySessionId = { String id ->
		MemcacheService cacheBySessionId = MemcacheServiceFactory.getMemcacheService("PlayerCache")
	    if (!cacheBySessionId) {
	    		throw new RuntimeException("Failed to look up PlayerCache")
	    }
	    cacheBySessionId.get(id)
	}

}
